<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Storage;

class Setting extends Model
{
    const IMAGE_TYPE = ['png', 'jpg', 'jpeg', 'gif', 'ico'];

    protected $fillable = ['name', 'slug', 'value', 'remark', 'group'];

    public static function getSettings($group = null)
    {
        $collect = Cache::remember('settings', 1440, function () {
            return self::query()->get();
        });
        if ($group) {
            return $collect->where('group', $group) ?: collect([]);
        }
        return collect($collect);
    }

    public static function createOrUpdate(Collection $collection, $group = 'default')
    {
        //配置项更新
        foreach ($collection as $item) {
            $item['group'] = $group;
            $setting = self::query()->where('group', $group)->where('slug', $item['slug'])->first();
            //如果是文件，保存文件，返回地址
            if ($item['value'] instanceof UploadedFile) {
                $extension = $item['value']->guessExtension();
                if (!in_array($extension, self::IMAGE_TYPE)) {
                    continue;
                }
                $item['value'] = $item['value']->storeAs('uploads/settings', $item['slug'] . '.' . $extension);
            }
            if ($setting instanceof self) {
                $setting->update($item);
            } else {
                self::query()->create($item);
            }
        }
        Cache::forget('settings');
    }

    public static function getReviewName($role)
    {
        if ($role == 1) {
            return self::query()->where('slug', 'admin_review_name')->value('value') ?: '院级审批';
        } elseif ($role == 2) {
            return self::query()->where('slug', 'dept_review_name')->value('value') ?: '科室审批';
        } else {
            return '';
        }
    }
}
